<?php

namespace app\controllers;

use Yii;
use app\tools\Re;
use app\tools\Curl;
use app\models\User;
use app\models\OrderInfo;
use app\models\OrderInfoGood;

class AliPayController extends BaseController
{
	//支付宝支付
	public function actionPay() {
		$order_sn = Yii::$app->request->post('order_sn', '');
		$openid = Yii::$app->request->post('openid', '');
		$order = OrderInfo::find()->where(['order_type' => 1, 'order_sn' => $order_sn])->one();
    $good_list = OrderInfoGood::find()->where(['order_id' => $order->id])->all();
    if ($good_list) {
      foreach ($good_list as $v) {
        if ($v->good->store < $v->num) {
          return Re::data(null, '商品库存不足，无法下单', Re::ERROR);
        }
      }
    }
    $mch_key = Yii::$app->params['ali_pay_config']['mch_key'];
		//支付统一下单
		$param["appid"] = Yii::$app->params['ali_config']['appid'];
		$param["mch_id"] = Yii::$app->params['ali_pay_config']['appid'];
		$param["nonce_str"] = md5(time().rand().$order_sn);
		$param["body"] = '商品支付订单';
		$param["out_trade_no"] = $order_sn;
		$param["total_fee"] = $order->money * 100; //金额单位:分
		$param["spbill_create_ip"] = $this->getIp();
		$param["notify_url"] = Yii::$app->params['domain'] . '/ali-pay/notify-order';
		$param["trade_type"] = "JSAPI";
		$param["openid"] = $openid;
		$sign = $this->getSign($param, $mch_key);
		$param["sign"] = $sign;
		$xml = $this->ToXml($param);
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		$response = $this->curl($url, $xml);
		$res = json_decode(json_encode(simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA)));
		//生成新的签名给前端支付
		$pay_param['appId'] = $res->appid;
		$pay_param['timeStamp'] = time();
		$pay_param['nonceStr'] = $res->nonce_str;
		$pay_param['package'] = 'prepay_id=' . $res->prepay_id;
    $pay_param['signType'] = 'MD5';
    $data = [
      'time_tamp' => time(),
      'nonce_str' => $res->nonce_str,
      'prepay_id' => $res->prepay_id,
      'pay_sign' => $this->getSign($pay_param, $merchant->mch_key)
    ];
		return Re::data(['data' => $data]);
	}

	//支付回调
	public function actionNotifyOrder() {
		$testxml  = file_get_contents("php://input");
		$jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
		$result = json_decode($jsonxml, true);//转成数组，
		if($result){
			//如果成功返回了
			$out_trade_no = $result['out_trade_no'];
			if($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS'){
				$order = OrderInfo::find()->where(['order_type' => 1, 'order_sn' => $out_trade_no])->one();
				if ($order && !$order->state) {//待支付
          $order->pay_at = time();
          $order->state = 1;
          if (!$order->save()) {
            return Re::data(null, $order->showErrors(), Re::ERROR);
          }
          $good_list = OrderInfoGood::find()->where(['order_id' => $order->id])->all();
          if ($good_list) {
            foreach ($good_list as $v) {
              $v->good->sale_count += $v->num;
              $v->good->save();
            }
          }
        }
			}
    } else {
			return Re::data(null, '订单信息异常，请联系平台管理员', Re::ERROR);
		}
		$xml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
		echo $xml;
	}

	private function ToXml($param) {
		if(!is_array($param) || count($param) <= 0) {
    	throw new WxPayException("数组数据异常！");
    }
    $xml = "<xml>";
    foreach ($param as $key=>$val) {
      if (is_numeric($val)){
        $xml.="<".$key.">".$val."</".$key.">";
      } else{
        $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
      }
    }
    $xml.="</xml>";
    return $xml;
	}

  private function getIp() {
    $ip = "";
    $env = Yii::$app->params['env'];
    if ($env == 'dev') {//本地环境
      $ip = file_get_contents('http://pv.sohu.com/cityjson?ie=utf-8');
      preg_match('/{.+}/i', $ip, $m);
      $array = json_decode($m[0]);
      $ip = $array->cip;
    } else {
      if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $cip = $_SERVER["HTTP_CLIENT_IP"];
      } else if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
      } else if (!empty($_SERVER["REMOTE_ADDR"])) {
        $cip = $_SERVER["REMOTE_ADDR"];
      } else {
        $cip = '';
      }
      preg_match("/[\d\.]{7,15}/", $cip, $cips);
      $ip = isset($cips[0]) ? $cips[0] : 'unknown';
      unset($cips);
    }
    return $ip;
  }
}
